#coding:utf-8

import time
import os
import socket
import ujson
import network
import udp_json_msg_def as UTILPRO
from machine import Pin;
LOCAL_LISTEN_PORT_UDP=6667
p13 = Pin(13, Pin.OUT)    # create output pin on GPIO0
led_i=0
addr_list={}


#------------led----------------
def  led_show_poll():		
    global led_i
    if led_i % 2 == 0:
        p13.on()                 # set pin to "on" (high) level
    else:
        p13.off()                # set pin to "off" (low) level
    led_i = led_i + 1
    
#------------server var----------------
udp_server_address=None
local_ip_str=""
def udp_recv_init(local_ip):
    print("udp bind ip->,"+local_ip+",port="+str(LOCAL_LISTEN_PORT_UDP))
    if local_ip != "":
        udp_server_address=(local_ip,LOCAL_LISTEN_PORT_UDP)
    else:
        udp_server_address=('127.0.0.1',LOCAL_LISTEN_PORT_UDP)
        
    udp_server_skt=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    udp_server_skt.bind(udp_server_address)
    udp_server_skt.setblocking(False)
    return udp_server_skt;
def parse_udp_recv_data(udp_data):
    try:
        print("udp_data-->:")
        print(udp_data.decode())
        msg_dic = ujson.loads(udp_data.decode())
        print(msg_dic[UTILPRO.K_HEAD])
        print(msg_dic[UTILPRO.K_VER])
        print(msg_dic[UTILPRO.K_IP])
        print(msg_dic[UTILPRO.K_PORT])
        #解析命令
        if msg_dic[UTILPRO.K_HEAD] == UTILPRO.MSG_VAL_HEAD and msg_dic[UTILPRO.K_VER] == UTILPRO.KV_VER:
            if msg_dic[UTILPRO.K_IP] != "" and msg_dic[UTILPRO.K_PORT] != 0:
                global local_ip_str
                local_ip = local_ip_str
                local_port = 9999
                print("cmd %s" % (msg_dic[UTILPRO.K_CMD]))
                msg_rspn = UTILPRO.MSG_VAL_HD_ALL          
                if msg_dic[UTILPRO.K_CMD] == "scan":
                    body_data = {UTILPRO.K_IP: local_ip, UTILPRO.K_PORT: local_port,UTILPRO.KC_SCAN:UTILPRO.KC_SCAN_R}
                    msg_rspn.update(body_data)
                    send_udp_msg(str(msg_dic[UTILPRO.K_IP]), msg_dic[UTILPRO.K_PORT],ujson.dumps(msg_rspn));
                elif msg_dic[UTILPRO.K_CMD] == "set":
                    body_data = {UTILPRO.K_IP: local_ip, UTILPRO.K_PORT: local_port, UTILPRO.K_CMD: UTILPRO.KC_SET_R ,UTILPRO.K_RET:"OK"}
                    msg_rspn.update(body_data)
                    send_udp_msg(str(msg_dic[UTILPRO.K_IP]), msg_dic[UTILPRO.K_PORT],ujson.dumps(msg_rspn));
                elif msg_dic[UTILPRO.K_CMD] == "get":
                    if  msg_dic[UTILPRO.K_ID] == 1:
                        body_data = {UTILPRO.K_IP: local_ip, UTILPRO.K_PORT: local_port, UTILPRO.K_CMD:UTILPRO.KC_GET_R , "id":1, "val":1}
                        msg_rspn.update(body_data)
                        send_udp_msg(str(msg_dic[UTILPRO.K_IP]), msg_dic[UTILPRO.K_PORT],ujson.dumps(msg_rspn));
    except:
        print("recv data err="+udp_data)
    
def udp_server_recv(skt):
    # while 1:
    # print("recv poll")
    try:        
        data,addr=skt.recvfrom(1024)
        print( "got data from",addr)
        # print (data)
        parse_udp_recv_data(data)
    except:
        pass
def  get_self_addr():
    #获取本地的ip地址
    # ipv4s=socket.gethostbyname_ex(socket.gethostname())[2]
    for i in (network.AP_IF, network.STA_IF):
        global local_ip_str
        iface = network.WLAN(i)
        if iface.active() :
            print("ip addr on ws://%s,i=%d" % (iface.ifconfig()[0], i))
            if i == 0:
                local_ip_str = str(iface.ifconfig()[0])
                print("local ip="+ local_ip_str)

def  send_udp_msg(ip, port, data_msg):        
    print("send udp: ip=%s,port=%d, msg=%s" % (str(ip),port, data_msg))
    addr_target=(str(ip),int(port))
    sock_t=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    sock_t.sendto((data_msg).encode(), addr_target)
    sock_t.close()

def  main_poll():
    wifi_init()
    get_self_addr()
    skt_t = udp_recv_init(local_ip_str)
    index_t = 1;
    try:
        while True:
            udp_server_recv(skt_t);
            led_show_poll();
            time.sleep(0.2);
    except KeyboardInterrupt:
        pass
    skt_t.close()

def  wifi_init():
	# def do_connect():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('Imilab-Office', 'Imilab$88888')
		# wlan.connect('Imilab-Office', 'Imilab$88888') # 连接到指定ESSID网络
        while not wlan.isconnected():
            time.sleep(1);
        print('network config:', wlan.ifconfig());
if __name__ == '__main__':
    main_poll();
